package com.sunsheng.modules.juc;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class myCache {
    private volatile Map<String, Object> map = new HashMap<>();
    //创建读写锁
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在写" + key);
            TimeUnit.MICROSECONDS.sleep(300);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写完了" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public Object get(String key) {
        rwLock.writeLock().lock();
        Object r = null;
        try {
            System.out.println(Thread.currentThread().getName() + "正在读取" + key);
            TimeUnit.MICROSECONDS.sleep(300);
            r = map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取完成" + key);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }
        return r;
    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) throws InterruptedException {
        myCache m = new myCache();
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                m.put(num + "", num + "");

            }, i + "").start();
        }
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                m.get(num + "");

            }, i + "").start();
        }
    }
}
